package com.stp.rabbitmq.listener;

import com.rabbitmq.client.Channel;
import com.stp.rabbitmq.constant.QueueConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class CommonRabbitmqListener {

    /**
     * 普通
     */
    @RabbitListener(queues = {QueueConstant.COMMON_QUEUE})
    public void commonListener(Message message, Channel channel) throws IOException {
        String msg = new String(message.getBody(), StandardCharsets.UTF_8);
        System.out.println("接收到的消息："+msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 工作消息队列（Work Queue）模式
     * 可以多个监听者，监听同一个队列，多线程处理消息
     */
    @RabbitListener(queues = {QueueConstant.COMMON_QUEUE})
    public void commonListener2(Message message, Channel channel) throws IOException {
        try {
            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            System.out.println("接收到的消息2："+msg);
            // 手动确认消息；原因：@RabbitListener中设置了ackMode = "MANUAL"
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            //失败确认
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            log.error(e.getMessage());
        }
    }


    /**
     * 手动确认
     * channel.basicNack 与 channel.basicReject 的区别在于basicNack可以批量拒绝多条消息，而basicReject一次只能拒绝一条消息。
     * @param message
     * @param channel
     */
    @RabbitListener(queues = {QueueConstant.COMMON_QUEUE})
    public void commonAckListener(Message message, Channel channel) throws IOException {
        try {
            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            System.out.println("接收到的消息2："+msg);
            // 手动确认消息；原因：@RabbitListener中设置了ackMode = "MANUAL"
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            log.error(e.getMessage());
        }
    }
}
